// 处理 趋势 箭头
export function trend(value) {
  let str = ''
  let color = ''
  let pnt = value
  if (pnt === '-') {
    str = '-'
  } else if (pnt === '0.00') {
    str = '0%'
  } else if (pnt.length > 1 && pnt.indexOf('-') !== -1) {
    color = '#00CBE4'
    str = `↓${pnt.slice(1)}%`
  } else {
    color = '#FF4500'
    str = `↑${pnt.slice(0)}%`
  }
  return `<i style="font-style:normal;color:${color};">${str}</i>`
}

/**
 * 处理昨日菜价趋势箭头
 */
export const processPntAndSat = pntOrSat => {
  if (pntOrSat === '-') {
    return '-'
  } else if (pntOrSat === '0') {
    return '-'
  } else if (pntOrSat.length > 1 && pntOrSat.indexOf('-') !== -1) {
    return `↓${pntOrSat.slice(1)}%`
  } else {
    return `↑${pntOrSat.slice(0)}%`
  }
}

/**
 * 格式化日期
 * 年/月/日
 */
export function formatDate(date) {
  if (!date) {
    date = new Date()
  }
  if (typeof date === 'string') {
    date = new Date(date)
  }
  let year = date.getFullYear()
  let mon = date.getMonth() + 1
  if (mon < 10) {
    mon = '0' + mon
  }
  let day = date.getDate()
  if (day < 10) {
    day = '0' + day
  }
  return year + '/' + mon + '/' + day
}

/**
 * 格式化日期
 * 年-月-日
 */
export function formatDate2(date) {
  if (!date) {
    date = new Date()
  }
  if (typeof date === 'string') {
    date = new Date(date)
  }
  let year = date.getFullYear()
  let mon = date.getMonth() + 1
  if (mon < 10) {
    mon = '0' + mon
  }
  let day = date.getDate()
  if (day < 10) {
    day = '0' + day
  }
  return year + '-' + mon + '-' + day
}

export function formatDate5(date) {
  if (!date) {
    date = new Date()
  }
  if (typeof date === 'string') {
    date = new Date(date)
  }
  let year = date.getFullYear()
  let mon = date.getMonth() + 1
  if (mon < 10) {
    mon = '0' + mon
  }
  let day = date.getDate()
  if (day < 10) {
    day = '0' + day
  }
  return [`${year}年${mon}月${day}日`, `${year}年${mon}月`, `${year}年`]
}

export function formatDate3(date, fmt) {
  var o = {
    "M+" : date.getMonth()+1,                 //月份
    "d+" : date.getDate(),                    //日
    "h+" : date.getHours(),                   //小时
    "m+" : date.getMinutes(),                 //分
    "s+" : date.getSeconds(),                 //秒
    "q+" : Math.floor((date.getMonth()+3)/3), //季度
    "S"  : date.getMilliseconds()             //毫秒
};
if(/(y+)/.test(fmt)) {
        fmt=fmt.replace(RegExp.$1, (date.getFullYear()+"").substr(4 - RegExp.$1.length));
}
 for(var k in o) {
    if(new RegExp("("+ k +")").test(fmt)){
         fmt = fmt.replace(RegExp.$1, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
     }
 }
return fmt;
}

// 处理 金额超过万元
export function saleAmount(value) {
  let unit = ''
  if (value === '-') {
    value = 0
    unit = '元'
  }
  let saleAmount = value / 100
  if (saleAmount > 9999) {
    saleAmount = `${(saleAmount / 10000).toFixed(2)}`
    unit = '万元'
  } else {
    saleAmount = `${saleAmount}`
    unit = '元'
  }
  return [saleAmount, unit]
}

// 处理默认值
export function isNil(obj) {
  return isNullEmptyOrUndefined(obj)
}
export function isNullEmptyOrUndefined(obj) {
  if (typeof obj === typeof '') {
    return obj.trim().length < 1
  }

  if (typeof obj === typeof 0 || typeof obj === typeof false) {
    return false
  }

  if (typeof obj === 'undefined' || obj === null) {
    return true
  } else {
    return false
  }
}

/**
 * 权鉴
 * @param {*} name 即将跳转的路由name
 * @param {*} access 用户权限数组
 * @param {*} routes 路由列表
 * @description 用户是否可跳转到该页
 */
export const canTurnTo = (name, access, routes) => {
  const routePermissionJudge = list => {
    return list.some(item => {
      if (item.children && item.children.length) {
        return routePermissionJudge(item.children)
      } else if (item.name === name) {
        return hasAccess(access, item)
      }
    })
  }
  return routePermissionJudge(routes)
}

/**
 * @param {*} access 用户权限数组，如 ['super_admin', 'admin']
 * @param {*} route 路由列表
 */
const hasAccess = (access, route) => {
  if (route.meta && route.meta.access) {
    return hasOneOf(access, route.meta.access)
  } else return true
}

/**
 * @param {Array} target 目标数组
 * @param {Array} arr 需要查询的数组
 * @description 判断要查询的数组是否至少有一个元素包含在目标数组中
 */
export const hasOneOf = (target, arr) => {
  return target.some(_ => arr.indexOf(_) > -1)
}

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string}
 */
export function parseTime(time, cFormat) {
  if (arguments.length === 0) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string') && (/^[0-9]+$/.test(time))) {
      time = parseInt(time)
    }
    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{(y|m|d|h|i|s|a)+}/g, (result, key) => {
    let value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') { return ['日', '一', '二', '三', '四', '五', '六'][value ] }
    if (result.length > 0 && value < 10) {
      value = '0' + value
    }
    return value || 0
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = url.split('?')[1]
  if (!search) {
    return {}
  }
  return JSON.parse(
    '{"' +
      decodeURIComponent(search)
        .replace(/"/g, '\\"')
        .replace(/&/g, '","')
        .replace(/=/g, '":"')
        .replace(/\+/g, ' ') +
      '"}'
  )
}
